<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryPageApi, addStrategyApi, queryInfoApi, updateStrategyApi, deleteStrategyApi } from '@/api/strategy'

//状态列表数据
const states = ref([{ name: '正常', value: 1 }, { name: '禁用', value: 0 }])
//文章列表数据
const strategyList = ref([])

const searchStrategy = ref({
  title: '',
  authorId: '',
  gameId: '',
  state: '', 
  date: [],
  begin: '',
  end: ''
})

//侦听date属性
watch(
  () => searchStrategy.value.date,
  (newValue, oldValue) => {
     if(newValue.length == 2){
      searchStrategy.value.begin = newValue[0]
      searchStrategy.value.end = newValue[1]
     }else {
      searchStrategy.value.begin = ''
      searchStrategy.value.end = ''
     }
  }
)

//声明token
const token = ref('')

onMounted(async () => {
  handleSearch()

  //加载localStorage存储的用户登录信息
  const loginUser =  localStorage.getItem('loginUser');
  if(loginUser){
    token.value = JSON.parse(loginUser).token
  }
})

//查询文章
const handleSearch = async () => {
  console.log('Search:', searchStrategy.value)
  const result = await queryPageApi(
    searchStrategy.value.title || '', 
    searchStrategy.value.authorId || '', 
    searchStrategy.value.gameId || '',
    searchStrategy.value.state || '', 
    searchStrategy.value.begin || '', 
    searchStrategy.value.end || '', 
    currentPage.value, 
    pageSize.value
  );
  if(result.code){
    strategyList.value = result.data.records
    total.value = result.data.total
  }
}

const handleReset = () => {
  // 清空表单
  searchStrategy.value = {
    title: '',
    authorId: '',
    gameId: '',
    state: '', 
    date: [],
    begin: '',
    end: ''
  }
  // 触发日期变更监听器
  searchStrategy.value = { ...searchStrategy.value }
  handleSearch()
}

// 分页配置
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

// 对话框配置
const dialogVisible = ref(false)
const dialogTitle = ref('')
const userFormRef = ref(null)
const strategy = ref({})

//编辑文章
const handleEdit = async (id) => {
  console.log('Edit:', id)
  const result = await queryInfoApi(id);
  if(result.code){
    dialogVisible.value = true
    dialogTitle.value = '修改文章'
    // 确保数据结构正确
    strategy.value = {
      id: result.data.id,
      title: result.data.title,
      content: result.data.content,
      authorId: result.data.authorId,
      gameId: result.data.gameId,
      state: result.data.state
    }
  }
  
  userFormRef.value.resetFields()
}

// 删除单个文章
const handleDelete = async (id) => {
  //弹出一个确认框, 如果确认, 就删除;
  ElMessageBox.confirm('确定删除该文章吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 删除文章
    const result = await deleteStrategyApi(id);
    if(result.code){
      ElMessage.success('删除文章成功') 
      handleSearch()
    }else{
      ElMessage.error(result.msg)
    }
  })
}

//新增文章
const addStrategy = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增文章'
  strategy.value = {
    title: '',
    content: '',
    authorId: '',
    gameId: '',
    state: 1
  }
  userFormRef.value.resetFields()
}

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ],
  authorId: [
    { required: true, message: '请输入作者ID', trigger: 'blur' }
  ],
  gameId: [
    { required: true, message: '请输入游戏ID', trigger: 'blur' }
  ],
  state: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

//保存文章
const save = async () => {
  await userFormRef.value.validate(async (valid) => {
    if(valid) {
      let result
      if(strategy.value.id){ //存在ID, 修改
        result = await updateStrategyApi(strategy.value);
      }else { //不存在ID, 新增
        result = await addStrategyApi(strategy.value);
      }
      if(result.code){
        ElMessage.success('保存文章成功')
        dialogVisible.value = false
        handleSearch()
      }else { 
        ElMessage.error(result.msg)
      }
    }
  })
}

// 存储选中的 ID
const selectedIds = ref([]);

// 处理复选框选择变化的函数
function handleSelectionChange(selection) {
  const ids = selection.map(item => item.id);
  selectedIds.value = ids;
}

//批量删除文章
const deleteByIds = async () => {
  //弹出一个确认框, 如果确认, 就删除;
  ElMessageBox.confirm('确定删除选中文章吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 删除文章
    const result = await deleteStrategyApi(selectedIds.value);
    if(result.code){
      ElMessage.success('删除文章成功')
      handleSearch()
    }else{
      ElMessage.error(result.msg)
    }
  })
}
</script>

<template> 
<h1>文章管理</h1> <br>
  <el-form :inline="true" :model="searchStrategy">
    <el-form-item label="标题">
      <el-input v-model="searchStrategy.title" placeholder="请输入文章标题"></el-input>
    </el-form-item>

    <el-form-item label="作者ID">
      <el-input v-model="searchStrategy.authorId" placeholder="请输入作者ID"></el-input>
    </el-form-item>

    <el-form-item label="游戏ID">
      <el-input v-model="searchStrategy.gameId" placeholder="请输入游戏ID"></el-input>
    </el-form-item>

    <el-form-item label="状态">
      <el-select v-model="searchStrategy.state" placeholder="请选择">
        <el-option label="正常" value="1"></el-option>
        <el-option label="禁用" value="0"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="发布日期">
      <el-date-picker
        v-model="searchStrategy.date"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
      ></el-date-picker>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">清空</el-button>
    </el-form-item>
  </el-form>


  <el-button type="primary" @click="addStrategy"> + 新增文章</el-button>
  <el-button type="danger" @click="deleteByIds"> - 批量删除</el-button>
  <br><br>

  <!-- 表格 -->
  <el-table :data="strategyList" border style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="50" align="center"></el-table-column>
    <el-table-column prop="title" label="标题" width="200" align="center"></el-table-column>
    <el-table-column prop="authorId" label="作者ID" width="100" align="center"></el-table-column>
    <el-table-column prop="gameId" label="游戏ID" width="100" align="center"></el-table-column>
    <el-table-column prop="viewCount" label="浏览量" width="100" align="center"></el-table-column>
    <el-table-column prop="likeCount" label="点赞数" width="100" align="center"></el-table-column>
    <el-table-column label="状态" width="80" align="center">
      <template #default="scope" >
        {{ scope.row.state == 1 ? '正常' : '禁用' }}
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="发布日期" width="150" align="center"></el-table-column>
    <el-table-column prop="updateTime" label="最后更新时间" width="150" align="center"></el-table-column>
    <el-table-column label="操作" fixed="right" align="center">
      <template #default="scope">
        <el-button size="small" type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <br>

  <!-- 分页 -->
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-sizes="[10, 20, 30, 40]"
    :page-size="pageSize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
  >
  </el-pagination>

  <!-- 新增/修改文章的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form ref="userFormRef" :model="strategy" :rules="rules" label-width="80px">
        <!-- 基本信息 -->
         <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="标题" prop="title">
              <el-input v-model="strategy.title" placeholder="请输入文章标题，2-100个字"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="作者ID" prop="authorId">
              <el-input v-model="strategy.authorId" placeholder="请输入作者ID"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="游戏ID" prop="gameId">
              <el-input v-model="strategy.gameId" placeholder="请输入游戏ID"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="state">
              <el-select v-model="strategy.state" placeholder="请选择状态" style="width: 100%;">
                <el-option v-for="state in states" :key="state.name" :label="state.name" :value="state.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="内容" prop="content">
              <el-input v-model="strategy.content" type="textarea" :rows="8" placeholder="请输入文章内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </span>
      </template>
  </el-dialog>

</template>

<style scoped> 
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>